package cn.shuibo.advice;

import cn.shuibo.util.BaseAES;
import cn.shuibo.util.RSAUtils;
import cn.shuibo.util.ServiceSafety;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;

/**
 * Author:Bobby
 * DateTime:2019/4/9
 **/
public class DecryptHttpInputMessage implements HttpInputMessage{

    private Logger log = LoggerFactory.getLogger(this.getClass());
    private HttpHeaders headers;
    private InputStream body;


    public DecryptHttpInputMessage(HttpInputMessage inputMessage, String privateKey, String charset, boolean showLog,String type,String secretKey) throws Exception {

        if (StringUtils.isEmpty(privateKey) &&  type.equals("RSA")) {
            throw new IllegalArgumentException("privateKey is null");
        }
        if (StringUtils.isEmpty(secretKey) &&  !type.equals("RSA")) {
            throw new IllegalArgumentException("secretKey is null");
        }

        this.headers = inputMessage.getHeaders();
        String content = new BufferedReader(new InputStreamReader(inputMessage.getBody()))
                .lines().collect(Collectors.joining(System.lineSeparator()));
        String decryptBody;
        if (content.startsWith("{")) {
            log.info("Unencrypted without decryption:{}", content);
            decryptBody = content;
        } else {
            StringBuilder json = new StringBuilder();
            content = content.replaceAll(" ", "+");

            if (!StringUtils.isEmpty(content)) {
                String[] contents = content.split("\\|");
                for (String value : contents) {
                    String result;
                    switch (type){
                        case "AES":
                            value = BaseAES.decrypt(content, secretKey);
                            break;
                        case "SECRET":
                            value = ServiceSafety.decrypt(content, secretKey);
                            break;
                        case "RSA":
                        default:
                            value = new String(RSAUtils.decryptDataOnJavaPrivate(value,privateKey).getBytes(), charset);
                            break;
                    }
                    json.append(value);
                }
            }
            decryptBody = json.toString();
            if(showLog) {
                log.info("Encrypted data received：{},After decryption：{}", content, decryptBody);
            }
        }
        this.body = new ByteArrayInputStream(decryptBody.getBytes());
    }

    @Override
    public InputStream getBody(){
        return body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return headers;
    }
}
